import React, { useEffect } from "react";
import { RootState, useDispatch, useSelector } from "@/redux";
import { MetaProps } from "@/routers/interface";
import { message, notification } from "@/hooks/useMessage";
import { useLoaderData, useLocation, useNavigate } from "react-router-dom";
import { HOME_URL, LOGIN_URL, ROUTER_WHITE_LIST, LOGIN_AD_URL, LOGIN_WEB_URL } from "@/config";
import { loginToken } from "@/views/login/api/otherSystem.ts";
import { setToken } from "@/redux/modules/user.ts";
import { getTimeState } from "@/utils";
import { CheckCircleFilled } from "@ant-design/icons";

/**
 * @description Route guard component
 */
interface RouterGuardProps {
  children: React.ReactNode;
}
// 解析地址
/*function parseQueryParams(url: string): Record<string, string> {
  const queryParams: Record<string, string> = {};
  const queryString = url.split("?")[1] || url.split("&").slice(1).join("&");
  const urls = url.split("&")[0];
  const pairs = queryString.split("&");
  pairs.forEach(pair => {
    console.log(pair);
    const [key, value] = pair.split("=");
    queryParams[decodeURIComponent(key)] = decodeURIComponent(value);
    queryParams["urls"] = urls;
  });

  return queryParams;
}*/
function parseUrl(url: string): { queryParams: Record<string, string> } {
  const queryParams: Record<string, string> = {};

  // 获取路径和查询字符串部分
  // pathPart
  const [, queryStringPart] = url.split("?");

  // 处理查询字符串
  const queryString = queryStringPart || "";
  const pairs = queryString.split("&");
  pairs.forEach(pair => {
    const [key, value] = pair.split("=");
    if (key) {
      queryParams[decodeURIComponent(key)] = value ? decodeURIComponent(value) : "";
    }
  });

  return { queryParams };
}

function generateRandom7DigitNumber(): number {
  // 生成一个 1000000 到 9999999 之间的随机数
  const min = 1000000;
  const max = 9999999;
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

const random7DigitNumber = generateRandom7DigitNumber();

// 路由拦截配置
const RouterGuard: React.FC<RouterGuardProps> = props => {
  const loader = useLoaderData();
  const navigate = useNavigate();
  const { pathname, search } = useLocation();

  // Mount navigate to provide non-React function components or calls in custom React Hook functions
   window.$navigate = navigate;

  const token = useSelector((state: RootState) => state.user.token);
  const authMenuList = useSelector((state: RootState) => state.auth.authMenuList);
  const dispatch = useDispatch();
  // 路由跳转改造（login loginAd）
  useEffect(() => {
    const meta = loader as MetaProps;
    if (meta) {
      const title = import.meta.env.VITE_GLOB_APP_TITLE;
      document.title = meta?.title ? `${meta.title} - ${title}` : title;
    }

    // Routing whitelist
    if (ROUTER_WHITE_LIST.includes(pathname)) return;

    // Whether login page
    const isLoginPage = pathname === LOGIN_URL || pathname === LOGIN_AD_URL || pathname === LOGIN_WEB_URL;
    // If there is menu data, token, or login on the accessed page, redirect to the home page
    if (authMenuList.length && token && isLoginPage) {
      return navigate(HOME_URL);
    }

    //初次登录
    if ((!token && !isLoginPage) || (!authMenuList.length && !token && !isLoginPage)) {
      // console.log("数据验证--", isLoginPage, pathname);
      // /ospauth/callback?token=1111112123123123123123123123&stat=123
      console.log(pathname, parseUrl(search));
      if (pathname == "/ospauth/callback") {
        if (!parseUrl(search).queryParams.token) {
          message.error("验证失败请重新登录！");
          // 跳转到统一认证登录

          return navigate(LOGIN_AD_URL, { replace: true });
        }

        loginToken({ token: parseUrl(search).queryParams.token, state: random7DigitNumber }).then((res: any) => {
          // console.log("获取数据---", res);
          if (res.code == 200) {
            // res.data.token;
            dispatch(setToken(res.data.token));
            notification.success({
              message: getTimeState(),
              description: "欢迎登录",
              icon: <CheckCircleFilled style={{ color: "#73d13d" }} />
            });
            window.location.href = HOME_URL;
          } else {
            message.error("验证失败请重新登录！");
            // 跳转到统一认证登录
            return navigate(LOGIN_AD_URL, { replace: true });
          }
        });
      }
      // 登录认证（后续接入内网改为统一认证）
      // return navigate(LOGIN_AD_URL, { replace: true });
      return navigate(LOGIN_WEB_URL);
      // return navigate(LOGIN_URL, { replace: true });
    }
  }, [loader]);

  return props.children;
};

export default RouterGuard;
